package com.crois.barrier.web.filter;

import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author Hou Ze Yu
 * @description door webFilter
 * @date 2020/7/12
 */
public abstract class AbstractBarrierWebFilter implements WebFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        final ServerHttpResponse response = serverWebExchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        return doFilter(serverWebExchange, webFilterChain).switchIfEmpty(Mono.just(false))
                .flatMap(filterResult -> filterResult ? webFilterChain.filter(serverWebExchange) : doResponse(serverWebExchange));
    }

    /***
     *  模版方法 子类 去实现
     * @param serverWebExchange
     * @param webFilterChain
     * @return 返回 true 则 表示允许执行下一个filter false 不执行 下一个 执行 doResponse
     */
    public abstract Mono<Boolean> doFilter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain);

    /***
     * 模版方法 子类 去实现
     * @param serverWebExchange
     * @return
     */
    public abstract Mono<Void> doResponse(ServerWebExchange serverWebExchange);
}
